<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="试题类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择试题类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CHONGQING_TEST_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试题描述" prop="content">
        <Editor v-model="formData.content" height="150px" />
      </el-form-item>
      <!-- 选项相关 -->
      <div v-if="formData.type === GAP_FILLING">
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="formData.score" disabled />
        </el-form-item>
        <el-form-item label="填空个数">
          <el-input-number v-model="formData.gapCount" placeholder="0" min="1" step="1" />
        </el-form-item>
        <el-form-item label="填空配置">
          <el-table :data="formData.testGaps" boder="true" stripe="true">
            <el-table-column label="答案文字" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.content" />
              </template>
            </el-table-column>
            <el-table-column label="分值" align="center" width="180px">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.score"
                  placeholder="0"
                  precision="1"
                  min="0"
                  step="1"
                />
              </template>
            </el-table-column>
            <el-table-column label="得分规则" align="center" width="180px">
              <template #default="scope">
                <el-select v-model="scope.row.rule" placeholder="请选择得分规则">
                  <el-option label="完全匹配得分" value="1" />
                  <el-option label="包含答案得分" value="2" />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div v-if="formData.type === SINGLE_SELECT || formData.type === MULTI_SELECT">
        <el-form-item label="分值" prop="score">
          <el-input-number
            v-model="formData.score"
            placeholder="0.5"
            precision="1"
            min="1"
            step="1"
          />
        </el-form-item>
        <el-form-item label="选项个数">
          <el-input-number v-model="formData.optionCount" placeholder="0" min="1" step="1" />
        </el-form-item>
        <el-form-item label="选项配置">
          <el-table :data="formData.testOptions" boder="true" stripe>
            <el-table-column label="选项文字" align="center">
              <template #default="scope">
                <el-input type="textarea" size="large" v-model="scope.row.content" />
              </template>
            </el-table-column>
            <el-table-column label="图片" align="center" width="120px">
              <template #default="scope">
                <UploadImg height="100px" width="100px" v-model="scope.row.picture" />
              </template>
            </el-table-column>
            <el-table-column label="正确答案" align="center" width="100px">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.correct"
                  @click="switchChange(scope.row.orderId, scope.row.correct)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <el-form-item label="难度" prop="difficulty">
        <el-rate v-model="formData.difficulty" />
      </el-form-item>
      <el-form-item label="知识点" prop="knowledgePoint">
        <el-input v-model="formData.knowledgePoint" type="textarea" placeholder="请输入知识点" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TestApi from '@/api/vr/test'
import { TestGap, TestOption } from '@/api/vr/test'
import UploadImg from '@/components/UploadFile/src/UploadImg.vue'
import Editor from '@/components/Editor/src/Editor.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const SINGLE_SELECT = 1 // 单选
const MULTI_SELECT = 2 // 多选
const GAP_FILLING = 3 // 填空
// const testGaps = ref<TestGap[]>([])
// const testOptions = ref<TestOption[]>([])
const formData = ref<TestApi.TestVO>({
  type: undefined,
  score: 0,
  content: '',
  optionCount: 0,
  testOptions: [],
  gapCount: 0,
  testGaps: [],
  difficulty: 0,
  knowledgePoint: ''
})

// interface TestOption {
//   id?: number
//   testId?: number
//   orderId: number
//   content: string
//   picture: string
//   correct: boolean
// }
//
// interface TestGap {
//   id?: number
//   testId?: number
//   orderId: number
//   content: string
//   score: number
//   rule: number | undefined
// }
// 侦听填空个数的改变，增加或删除填空
watch(
  () => formData.value.gapCount,
  (newCount) => {
    if (formData.value.type != GAP_FILLING) {
      return
    }
    let def = newCount - formData.value.testGaps.length
    if (def > 0) {
      for (let i = 0; i < def; i++) {
        const cur = formData.value.testGaps.length + 1
        const testGap: TestGap = {
          orderId: cur,
          content: '填空' + cur,
          score: 0,
          rule: 0
        }
        formData.value.testGaps.push(testGap)
      }
    } else if (def < 0) {
      formData.value.testGaps.splice(newCount)
    }
  }
)
// 侦听选项个数的改变，增加或删除选项
watch(
  () => formData.value.optionCount,
  (newCount) => {
    console.log('我是选项')
    if (formData.value.type != SINGLE_SELECT && formData.value.type != MULTI_SELECT) {
      return
    }
    let def = newCount - formData.value.testOptions.length
    if (def > 0) {
      for (let i = 0; i < def; i++) {
        const cur = formData.value.testOptions.length + 1
        const testOption: TestOption = {
          orderId: cur,
          content: '选项' + cur,
          picture: '',
          correct: false
        }
        formData.value.testOptions.push(testOption)
      }
    } else if (def < 0) {
      formData.value.testOptions.splice(newCount)
    }
  }
)

watch(
  () => formData.value.testGaps,
  () => {
    if (formData.value.type != GAP_FILLING) {
      return
    }
    if (formData.value.testGaps) {
      let totalScore = 0
      for (let gap of formData.value.testGaps) {
        totalScore += gap.score
      }
      formData.value.score = totalScore
      console.log(totalScore)
    }
  },
  { deep: true }
)

const switchChange = (orderId: number, correct: boolean) => {
  // 单项选择，当选择某个选项为正确选项时，将其他选项的switch关闭
  if (correct && formData.value.type == SINGLE_SELECT) {
    formData.value.testOptions.forEach((element) => {
      if (element.orderId !== orderId) {
        element.correct = false
      }
    })
  }
}

const formRules = reactive({
  type: [{ required: true, message: '试题类型不能为空', trigger: 'change' }],
  content: [{ required: true, message: '试题描述不能为空', trigger: 'change' }],
  score: [{ required: true, message: '分值不能为空', trigger: 'blur' }],
  difficulty: [{ required: true, message: '难度不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TestApi.getTest(id)
      if (formData.value.type == GAP_FILLING) {
        formData.value.gapCount = formData.value.testGaps.length
      } else {
        formData.value.optionCount = formData.value.testOptions.length
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TestApi.TestVO
    if (formType.value === 'create') {
      await TestApi.createTest(data)
      message.success(t('common.createSuccess'))
    } else {
      await TestApi.updateTest(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
/** 重置表单 */
const resetForm = () => {
  // testOptions.value = []
  // testGaps.value = []
  formData.value = {
    type: undefined,
    score: 0,
    content: '',
    optionCount: 0,
    testOptions: [],
    gapCount: 0,
    testGaps: [],
    difficulty: 0,
    knowledgePoint: ''
  }
  formRef.value?.resetFields()
}
</script>
